package org.ithink.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.SAXReader;

public class SoapUtil {
  private String url;
  private String xml;
  private static int TIMEOUT = 10 * 60 * 1000;//默认为三分钟
  
  public SoapUtil(String url, String xml){
    this.url = url;
    this.xml = xml;
  }

  public static void main(String[] args) {
    String reqStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
        + "<SOAP-ENV:Body>"
        + "<ns1:NCMMP_200101 SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:ns1=\"urn:HyrjService\">"
        + "<in200101 xsi:type=\"ns1:In200101\">" 
        + "<i101_01>230125</i101_01>" 
        + "</in200101>"
        + "</ns1:NCMMP_200101>" 
        + "</SOAP-ENV:Body>" 
        + "</SOAP-ENV:Envelope>";
    String reqUrl = "http://125.46.57.67/nccmintf230125/NCCMIntf.aspx";
    SoapUtil soapUtil = new SoapUtil(reqUrl, reqStr);
    try {
      soapUtil.send();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public String send() throws Exception{
    // 选择HttpURLConnection的方式
    return sendWithCommons(this.url, this.xml);
  }

  /**
   * 用java.net.HttpURLConnection的方式调用
   */
  public String sendWithNet(String requestUrl, String soapXml) throws Exception  {

    PrintWriter printWriter = null;
    Reader reader = null;
    BufferedReader bufferedReader = null;
    StringBuffer responseResult = new StringBuffer();
    // StringBuffer params = new StringBuffer();
    HttpURLConnection httpURLConnection = null;
    Document document = null;
    String line = "";

    try {
      URL realUrl = new URL(requestUrl);

      // 打开和URL之间的连接
      httpURLConnection = (HttpURLConnection) realUrl.openConnection();
      // 设置通用的请求属性
      // httpURLConnection.setRequestProperty("accept", "*/*");
      // httpURLConnection.setRequestProperty("connection", "Keep-Alive");
      httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      httpURLConnection.setRequestProperty("Content-Length", String.valueOf(soapXml.length()));
      httpURLConnection.setRequestProperty("SOAPAction", "POST");
      // httpURLConnection.setRequestMethod("");
      // 发送POST请求必须设置如下两行
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setDoInput(true);
      // 获取URLConnection对象对应的输出流
      printWriter = new PrintWriter(httpURLConnection.getOutputStream());
      // 发送请求参数
      printWriter.write(soapXml.toString());
      // flush输出流的缓冲
      printWriter.flush();
      // 根据ResponseCode判断连接是否成功
      int responseCode = httpURLConnection.getResponseCode();
      System.out.println(httpURLConnection.getResponseMessage());
      if (responseCode != HttpStatus.SC_OK) {
        throw new RuntimeException("发包失败！");
      }
      // 返回String
      // 定义BufferedReader输入流来读取URL的ResponseData
      reader = new InputStreamReader(httpURLConnection.getInputStream(), Charset.forName("utf-8"));
      bufferedReader = new BufferedReader(reader);
      while ((line = bufferedReader.readLine()) != null) {
        responseResult.append(line).append("\n");
      }

      // 返回Domcumnt
      SAXReader saxreader = new SAXReader();
      document = saxreader.read(new InputStreamReader(httpURLConnection.getInputStream(), Charset.forName("utf-8")));
      document = DocumentHelper.parseText(responseResult.toString());
      
      System.out.println(document.asXML());

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      httpURLConnection.disconnect();
      try {
        if (printWriter != null) {
          printWriter.close();
        }
        if (bufferedReader != null) {
          bufferedReader.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return responseResult.toString();
    // return document;
  }
  
  /**
   * 用org.apache.commons.httpclient.HttpClient的方式调用
   */
  private String sendWithCommons(String url, String requestData) throws Exception {
    String result = "";
    HttpClient client = null;
    PostMethod postMethod = null;
    StringRequestEntity requestEntity = null;

    try {
      client = new HttpClient();
      client.getParams().setIntParameter("http.socket.timeout",SoapUtil.TIMEOUT);
      postMethod = new PostMethod(url);
      requestEntity = new StringRequestEntity(requestData, "text/xml", "UTF-8");
      
      postMethod.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
      postMethod.setRequestHeader("SOAPAction", "POST");
      postMethod.setRequestEntity(requestEntity);
      
      int status = client.executeMethod(postMethod);
      if (status == HttpStatus.SC_OK) {
        result = postMethod.getResponseBodyAsString();
      } else {
        throw new RuntimeException("发包失败！");
      }

    } catch (Exception ex) {
      throw new Exception(ex);
    } finally {
      postMethod.releaseConnection();
    }
    return result;

  }

}
